package com.example.rdcproject.ving.notes.view.Admin;

import com.example.rdcproject.ving.notes.service.ConnectionPool;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class BooksView extends JFrame{
    private DefaultTableModel model;
    private JTable table;

    private ConnectionPool connectionPool = ConnectionPool.getInstance();
    private Connection connection;

    public BooksView() {

            setTitle("词书列表");
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setSize(500, 500);
            setLocationRelativeTo(null);

            // 创建表格模型
            model = new DefaultTableModel();
            model.addColumn("编号");
            model.addColumn("书名");

            // 创建表格，并设置模型
            table = new JTable(model);

            // 创建滚动面板，并将表格添加到滚动面板中
        JScrollPane scrollPane = new JScrollPane(table);
            getContentPane().add(scrollPane, BorderLayout.CENTER);

            // 读取数据库数据，添加到表格模型中
            loadData();

            setVisible(true);
        }

        private void loadData () {
            try {
                // 连接数据库
                connection = connectionPool.getConnection();
                // 创建 SQL 语句
                String sql = "select * from books";

                // 创建语句对象，并执行 SQL 查询
                Statement statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery(sql);

                // 将查询结果添加到表格模型中
                while (resultSet.next()) {
                    int id = resultSet.getInt("id");
                    String title = resultSet.getString("name");
                    model.addRow(new Object[]{id, title});
                }

                // 关闭连接
                statement.close();
                connectionPool.releaseConnection(connection);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

